package com.czz.manage.controller.admin;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.czz.common.exception.CustomerException;
import com.czz.common.exception.ResultCodeEnum;
import com.czz.common.vo.R;
import com.czz.manage.entity.Category;
import com.czz.manage.service.CategoryService;
import com.czz.manage.vo.CategoryNestedVo;
import com.czz.manage.vo.CategoryVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;


/**
 * @ClassName: CategoryAdminController
 * @Author Czz
 * @Date 2019/12/29
 * @Time 10:08
 **/
@RestController
@RequestMapping(value = "/admin/categories")
public class CategoryAdminController {

    @Autowired
    CategoryService categoryService;

    /**
    * @Description 分页查询所有课程分类嵌套列表
    * @Param [page, limit, category]
    * @Return com.czz.common.vo.R
    * @Author Czz
    * @Date 2020/3/10
    * @Time 10:55
    **/
    @GetMapping(value = "/{page}/{limit}")
    public R getCategoryPageList(@PathVariable Long page, @PathVariable Long limit,Category category){
        if (page <= 0 || limit <= 0){
            return R.setResult(ResultCodeEnum.INPUT_ERROR);
        }
        Page<CategoryNestedVo> pageParam = new Page<>(page, limit);
        pageParam.setRecords(categoryService.getCategoryPageList(pageParam,category));
        Long total = pageParam.getTotal();
        return R.ok().data("total", total).data("rows", pageParam.getRecords());
    }

    /**
    * @Description 根据id查询课程分类
    * @Param [id]
    * @Return com.czz.common.vo.R
    * @Author Czz
    * @Date 2020/3/10
    * @Time 20:25
    **/
    @GetMapping(value = "/{id}")
    public R getCategoryById(@PathVariable String id){
        if (StringUtils.isEmpty(id)){
            return R.setResult(ResultCodeEnum.INPUT_ERROR);
        }
        Category category = categoryService.getById(id);
        return R.ok().data("item",category);
    }

    /**
    * @Description 新增一级/二级课程分类
    * @Param [category]
    * @Return com.czz.common.vo.R
    * @Author Czz
    * @Date 2020/1/2
    * @Time 15:39
    **/
    @PostMapping(value = "")
    public R saveParentCategory(Category category){
        if (StringUtils.isEmpty(category.getName()) || StringUtils.isEmpty(category.getSort())) {
            return R.setResult(ResultCodeEnum.INPUT_ERROR);
        }
        //判断一级分类
        if (StringUtils.isEmpty(category.getParentId())){
            //判断一级分类是否存在
            Category parentCategory = categoryService.getParentCategoryByName(category.getName());
            if (!ObjectUtils.isEmpty(parentCategory)) return R.setResult(ResultCodeEnum.RESOURCE_EXISTS);
            categoryService.saveParentCategory(category);
            return R.ok();
        }
        //二级分类
        else{
            //判断一级分类中是否存在二级分类
            Category childCategory = categoryService.getChildCategoryByName(category.getName(),category.getParentId());
            if (!ObjectUtils.isEmpty(childCategory)) return R.setResult(ResultCodeEnum.RESOURCE_EXISTS);
            categoryService.saveChildCategory(category);
            return R.ok();
        }
    }

    /**
    * @Description 根据id更新一级/二级课程分类名称
    * @Param [id, name]
    * @Return com.czz.common.vo.R
    * @Author Czz
    * @Date 2020/1/3
    * @Time 11:52
    **/
    @PutMapping(value = "")
    public R updateCategory(Category category){
        if (StringUtils.isEmpty(category.getId()) || ObjectUtils.isEmpty(category)){
            return R.setResult(ResultCodeEnum.INPUT_ERROR);
        }
        categoryService.updateCategoryById(category);
        return R.ok();
    }

    /**
    * @Description 根据id删除一级/二级课程分类
    * @Param [id]
    * @Return com.czz.common.vo.R
    * @Author Czz
    * @Date 2020/1/3
    * @Time 11:55
    **/
    @DeleteMapping(value = "/{id}")
    public R deleteCategory(@PathVariable String id){
        if (StringUtils.isEmpty(id)){
            return R.setResult(ResultCodeEnum.INPUT_ERROR);
        }
        Boolean flag = categoryService.deleteCategoryById(id);
        if (flag) return R.ok();
        else return R.setResult(ResultCodeEnum.INPUT_ERROR).message("删除失败！该分类下还存在课程！");
    }

    /**
    * @Description Excel导入课程分类
    * @Param [file]
    * @Return com.czz.common.vo.R
    * @Author Czz
    * @Date 2020/1/4
    * @Time 10:33
    **/
    @PostMapping(value = "/import")
    public R batchImportCategory(@RequestParam("file") MultipartFile file){
        try{
            List<String> errorMsg = categoryService.batchImportCategory(file);
            if(errorMsg.size() == 0){
                return R.ok().message("批量导入成功");
            }else{
                return R.error().message("部分数据导入失败").data("errorMsgList", errorMsg);
            }

        }catch (Exception e){
            //无论哪种异常，只要是在excel导入时发生的，一律用转成自定义异常抛出
            throw new CustomerException(ResultCodeEnum.EXCEL_DATA_IMPORT_ERROR);
        }
    }

    /**
     * @Description 查询课程分类嵌套列表
     * @Param []
     * @Return com.czz.common.vo.R
     * @Author Czz
     * @Date 2020/2/23
     * @Time 16:13
     **/
    @GetMapping(value = "/nested")
    public R getCategoryNestedList(){
        List<CategoryNestedVo> categoryNestedVoList = categoryService.getCategoryNestedList();
        return R.ok().data("items",categoryNestedVoList);
    }
}
